import time
import binascii
import threading

DEBUG = "DEBUG"
INFO = "INFO"
ERROR = "ERROR"

helperLock = threading.Lock()

def log(msg, level=INFO):
    helperLock.acquire()
    now = time.strftime("[%Y-%m-%d %H:%M:%S]")
    if msg == "" or msg == None:
        return
    logInfo = now + ' [' + level + '] ' + msg + '\n'
    print(logInfo)
    with open("log.txt", 'a+') as file:
        file.write(logInfo)
    helperLock.release()

def getBit(data, index):
    if type(data) != int:
        return None
    if data & (1 << index):
        return 1
    else:
        return 0

def setBit(data, index, value):
    if type(data) != int:
        return None
    if value:
        return data | (1 << index)
    else:
        return data & ~(1 << index)

def getRangeBit(data, maxIndex, minIndex):
    if type(data) != int:
        return None
    res = 0
    for i in range(maxIndex - minIndex + 1):
        res += getBit(data, minIndex + i) << i
    return res

def dataValidation(data, offset = 2):
    res = 0
    for i in range(len(data) - offset):
        res += data[i]
    if data[-2] == getRangeBit(res, 7, 0):
        return True
    else:
        return False

def getSumCheck(data):
    res = 0
    for i in range(len(data)):
        res += data[i]
    return getRangeBit(res, 7, 0)

def hexToStyledStr(data):
    """
    将bytes或bytearray转换成带有空格的十六进制字符串
    :param data: bytes或bytearray数据
    :return: 带有空格的十六进制字符串
    """
    res = binascii.b2a_hex(data).decode('utf-8')
    t = ""
    for i in range(len(res)):
        if i % 2 != 0:
            t += res[i]
            t += ' '
        else:
            t += res[i]
    return t

def packSplite(pack, firstStamp, endStamp):
    """
    通过包的首尾标记来分割包
    一个包的结尾必跟着下一个包的开头，否则返回None
    开头和结尾标志必须出现在输入包的两端，否则返回None
    :param pack: 数据包
    :param firstStamp: 包的开头标志
    :param endStamp: 包的结尾标志
    """
    if pack[0] != firstStamp:
        return None
    packList = []
    firstIndex = 0
    for p in range(len(pack)):
        if p == len(pack) - 1:
            if pack[p] != endStamp:
                return None
            else:
                packList.append(pack[firstIndex: p + 1])
                break
        if pack[p] == endStamp and pack[p + 1] == firstStamp:
            packList.append(pack[firstIndex: p + 1])
            firstStamp = p + 1
            continue
    return packList
